<template>
    <!-- 搜索工作栏 -->
<ContentWrap :loading="loading">
  <el-form
    ref="queryFormRef"
    :inline="true"
    :model="queryParams"
    class="-mb-15px"
    label-width="68px"
  >
    <el-form-item label="订单号" prop="no">
      <el-input
        v-model="queryParams.no"
        class="!w-220px"
        clearable
        placeholder="请输入主订单号"        
      />
    </el-form-item>
    <el-form-item label="子订单号" prop="orderItemNo">
      <el-input
        v-model="queryParams.orderItemNo"
        class="!w-220px"
        clearable
        placeholder="请输入子订单号"        
      />
    </el-form-item>
    <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" class="!w-120px" clearable placeholder="全部">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>   
    <el-form-item label="发货果园">
      <el-select
          v-model="queryParams.orchardId"
          filterable
          reserve-keyword
          class="!w-200px"
          placeholder="请输入果园名称">
          <el-option
            v-for="item in orchardList"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button @click="handleQuery">
        <Icon class="mr-5px" icon="ep:search" />
        搜索
      </el-button>
      <el-button @click="resetQuery">
        <Icon class="mr-5px" icon="ep:refresh" />
        重置
      </el-button>  
      <el-button @click="exportHandle" type="primary" :loading="exportLoading">
        <Icon class="mr-5px" icon="ep:download" />
        导出
      </el-button> 
      <el-upload
          class="upload-demo"
          style="margin-left: 10px;"
          ref="batchDelivery"
          :action="uploadUrl"
          :multiple="false"
          :limit="1"
          :headers="{'Authorization': token, 'Tenant-Id': tenantId}"
          :on-success="handleUploadSuccess"
          :before-upload="handleBeforeUpload"
          :on-error="handleError"
          accept=".xls,.xlsx"
          :show-file-list="false"
          :auto-upload="true">
          <el-button type="warning"> <Icon class="mr-5px" icon="ep:upload" />批量发货</el-button>         
        </el-upload>  
    </el-form-item>
  </el-form>
</ContentWrap>

<!-- 列表 -->
<ContentWrap>
  <el-table v-loading="loading" :data="list">
    <el-table-column label="订单号" width="220" prop="no" >
      <template #default="{row}">
        <div>主单号：<span>{{row.no}}</span></div>
        <div>子单号：<span>{{row.orderItemNo}}</span></div>
      </template>
    </el-table-column>
    <el-table-column align="center" label="商品名称" width="210" prop="spuName" />
    <el-table-column align="center" label="商品图" min-width="120" prop="title" >
      <template #default="{ row }">
        <el-image
          :src="row.picUrl"
          class="!h-[45px] !w-[45px]"
          fit="contain"
          @click="imagePreview(row.picUrl)"
        >
          <template #error>
            <div class="image-slot">
              <icon icon="ep:picture" />
            </div>
          </template>
        </el-image>
      </template>
    </el-table-column>
    <el-table-column label="商品规格" prop="properties" width="120">
        <template #default="{ row }">
          <el-tag v-for="property in row.properties" :key="property.propertyId">
            {{ property.propertyName }}: {{ property.valueName }}
          </el-tag>
        </template>
    </el-table-column>
    <el-table-column align="center" label="发货果园" min-width="130" prop="orchardName" />
    <el-table-column align="center" label="收货人信息" width="260">
      <template #default="{row}">
        <!-- 快递发货  -->
        <div  class="flex flex-col">              
          <span>
              {{ row.receiverName }} &nbsp;&nbsp;&nbsp;&nbsp; 
              {{ row.receiverMobile }}          
          </span>
          <p>{{ row.receiverDetailAddress }}</p>
        </div>            
      </template>
    </el-table-column>
    <el-table-column align="center" label="订单状态" width="100">
          <template #default="{row}">
            <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="row.status" />
          </template>
    </el-table-column>
    <el-table-column
      :formatter="dateFormatter"
      align="center"
      label="下单时间"
      prop="createTime"
      width="180"
    />
    <el-table-column align="center" label="快递信息" min-width="120" prop="id">
      <template #default="{ row }">
        <span>{{row.expressName}}</span> &nbsp;&nbsp; <span>{{row.logisticsNo}}</span>
      </template>
    </el-table-column> 
    <el-table-column label="售后状态" prop="afterSaleStatus" width="100">
      <template #default="{ row }">
        <dict-tag
          :type="DICT_TYPE.TRADE_ORDER_ITEM_AFTER_SALE_STATUS"
          :value="row.afterSaleStatus"
        />
      </template>
    </el-table-column>    
    <el-table-column align="center" fixed="right" label="操作" min-width="200">
      <template #default="{ row }">
        <!-- <el-button link type="primary" @click="openDetail(row.id)"> 详情 </el-button> -->
        <el-button
          v-hasPermi="['trade:order:update']"
          link
          type="primary"
          v-if="row.status === TradeOrderStatusEnum.UNDELIVERED.status"
          @click="deliveryHandle(row)"
        >
          发货
        </el-button>
        <el-button
          v-hasPermi="['trade:orderItem:detail']"          
          link
          type="primary"
          @click="detailHandle(row.id)"
        >
          详情
        </el-button>
        <el-button
            v-hasPermi="['trade:after-sale:create']"
            link
            v-if="row.status !== TradeOrderStatusEnum.UNPAID.status 
                && row.status !== TradeOrderStatusEnum.CANCELED.status && row.afterSaleStatus == 0 "
            type="primary"
            @click="applyAfterSale(row)"
          >
            申请售后
        </el-button>       
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <Pagination
    v-model:limit="queryParams.pageSize"
    v-model:page="queryParams.pageNo"
    :total="total"
    @pagination="getList"
  />
</ContentWrap>

    <!-- 各种操作的弹窗 -->
  <OrderItemDeliveryForm ref="deliveryFormRef" @success="getList" />
  <AddAfterSaleForm ref="afterSaleFormRef" @success="getList" />

</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import { floatToFixed2 } from '@/utils'
import { createImageViewer } from '@/components/ImageViewer'
import * as TradeOrderApi from '@/api/mall/trade/order'
import OrderItemDeliveryForm from '@/views/mall/trade/order/form/OrderItemDeliveryForm.vue'
import AddAfterSaleForm from '@/views/mall/trade/order/form/AddAfterSaleForm.vue'
import * as OrchardApi from '@/api/mall/orchard/orchard'
import { checkPermi } from '@/utils/permission'
import download from '@/utils/download'
import { getAccessToken, getTenantId} from '@/utils/auth'

defineOptions({ name: 'OrderItemList' })

const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const queryFormRef = ref() // 搜索的表单Ref
const total = ref(0) // 列表的总页数
const list = ref<TradeOrderApi.OrderItemListRespVO[]>([]) // 列表的数据
const deliveryFormRef = ref() //发货表单
const afterSaleFormRef = ref() //申请售后表单
const orchardList = ref<OrchardApi.Orchard[]>([]) // 列表的数据

const { currentRoute, push } = useRouter() // 路由跳转
const message = useMessage() // 消息弹窗
  // 批量发货导入接口地址
const uploadUrl = import.meta.env.VITE_BATCH_DELIVERY_URL
const token = 'Bearer ' + getAccessToken()
const tenantId = getTenantId()

const queryParams = ref({
  orderNo: '',
  orderItemNo: '',
  orchardId: undefined,
  status: undefined,
  pageSize: 10,
  pageNo: 1
})

const getList = async () => {
  loading.value = true
  try {
    const data = await TradeOrderApi.getOrderItemPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = async () => {
  queryParams.value.pageNo = 1;
  console.log(queryParams)
  getList()
}

const exportHandle = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm('如果导出发货订单请将【订单状态】选择为‘待发货’状态')
    // 发起导出
    exportLoading.value = true
    const data = await TradeOrderApi.exportOrderItems(queryParams.value)
    let date = new Date()
    let fileName = dateFormatter2(date);
    console.log(fileName)
    download.excel(data, '发货订单.xls');
  } catch {

  } finally {
    exportLoading.value = false
  }
}

const handleUploadSuccess = (response, file, fileList) => {
  loading.value = false
  if(response && response.code == 0) {
    message.success(`发货成功【${response.data}】个订单`)
  }
}

const handleError = (err, file, fileList) => {
  loading.value = false
  message.error('上传失败')
  console.log(err)
}

const handleBeforeUpload = () => {
  loading.value = true
}

const uploadHandle = async () => {

}

const detailHandle = (id: number) => {
  push({ name: 'TradeOrderItemDetail', params: { id } })
}

const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value = {
  orderNo: '',
  orderItemNo: '',
  orchardId: undefined,
  status: undefined,
  pageSize: 10,
  pageNo: 1
}
  handleQuery();
}

const applyAfterSale = (item) => {
  afterSaleFormRef.value?.open(item)
}

const deliveryHandle = (item) => {
  deliveryFormRef.value?.open(item)
}
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

const getOrchardList = async () => {
  OrchardApi.getOrchardAll().then(res => {
    orchardList.value = res
  })
}

/** 激活时 */
onActivated(() => {
  getList()
  getOrchardList()
})

watch(
  () => currentRoute.value,
  () => {
    getList()
  }
)
/** 初始化 **/
onMounted(async () => {
  await getList()
  getOrchardList()
})
</script>
<style>
.upload-demo {
  width: 81px;
  height: 32px;
}
</style>
